<template>
  <van-card
      v-for="team in props.teamList"
      :key="team.id"
      :desc="`队伍描述： ${team.description}`"
      :title="team.name"
      :thumb="team.createUserVO?.avatarUrl"
  >
    <template #tags>
      <van-tag plain type="danger" style="margin-right: 8px; margin-top: 8px">{{
          teamStatusEnum[team.status]
        }}
      </van-tag>
      <van-tag v-if="new Date(team.expireTime) < new Date()" color="#7232dd" style="margin-right: 8px" plain>过期</van-tag>
      <van-tag v-for="tag in JSON.parse(team.createUserVO?.tags)" plain type="primary"
               style="margin-right: 8px; margin-top: 8px">
        {{ tag }}
      </van-tag>
    </template>
    <template #bottom>

      <div>
        {{ '队伍人数：' + team.joinUserVOList?.length + "/" + team.maxNum }}
        <van-image
            v-for="joinUser in team.joinUserVOList"
            round
            width="26"
            height="26"
            :src="joinUser.avatarUrl"
        />
      </div>

      <div v-if="team.expireTime">
        {{ '过期时间：' + dayjs(team.expireTime).format('YYYY-MM-DD HH:mm:ss') }}
      </div>
    </template>

    <template #footer>
      <!--      只有加入队伍的用户列表中不存在的用户才显示加入队伍按钮。 find函数：如果数组中找到满足条件的数据，就返回true。-->
      <van-button v-if="!team.joinUserVOList?.find(joinUserVo => joinUserVo.id === loginUser.id )" plain hairline
                  @click="doJoinTeam(team.id, team.status)" type="primary" size="small">
        <van-icon name="add-o" size="16" style="margin-right: 1px"/>
        加入队伍
      </van-button>
      <van-button v-if="team.captainId === loginUser.id" plain hairline
                  @click="doUpdateTeam(team.id)" type="primary" size="small">
        <van-icon name="edit"/>
        修改队伍
      </van-button>
      <van-button v-if="team.joinUserVOList?.find(joinUserVo => joinUserVo.id === loginUser.id) && team.joinUserVOList?.length > 1" plain hairline
                  @click="doQuitTeam(team.id)" type="primary" size="small">
        <van-icon name="cross"/>
        退出队伍
      </van-button>
      <van-button
          v-if="team.captainId === loginUser.id && team.joinUserVOList?.find(joinUserVo => joinUserVo.id === loginUser.id )"
          plain hairline
          @click="doDeleteTeam(team.id)" type="danger" size="small">
        <van-icon name="delete-o"/>
        解散队伍
      </van-button>
    </template>
  </van-card>
  <van-dialog v-model:show="showPasswordInput" title="请输入队伍密码" @confirm="doConfirm" @cancel="doCancel" show-cancel-button>
    <van-cell-group inset>
      <van-field v-model="password" type="password" placeholder="请输入密码"/>
    </van-cell-group>
  </van-dialog>
</template>

<script setup lang="ts">
import {TeamType} from "../models/team";
import {teamStatusEnum} from "../constants/teamConstant.ts";
import request from "../plugins/request.ts";
import {onMounted, ref} from "vue";
import {UserType} from "../models/user";
import {useUserStore} from "../stores/modules/user.ts";
import {useRouter} from "vue-router";
import dayjs from "dayjs";
const userStore = useUserStore();
const router = useRouter();

const showPasswordInput = ref(false)
const password = ref("")
// 记录要加入队伍的id
const joinTeamId = ref();

const loginUser: UserType = ref({
  ...userStore.currentLoginUserInfo
})
onMounted(() => {
  userStore.getCurrentLoginUser()
})

interface TeamCardListProps {
  teamList: TeamType[];
}

const props = withDefaults(defineProps<TeamCardListProps>(), {
  teamList: []
})
/**
 * 加入队伍
 * @param teamId
 * @param status
 */
const doJoinTeam = async (teamId: number, status: number) => {
  if (status === 2) {
    joinTeamId.value = teamId;
    showPasswordInput.value = true
    return;
  }
  const result = await request.post("/team/join", {
    teamId
  });
  if (result?.data.code === 200) {
    showSuccessToast('加入成功');
    window.location.reload()
  } else {
    showFailToast('加入失败，' + result.data.description);
  }
}
/**
 * 加入有密码的队伍
 */
const doConfirm = async () => {
  const result = await request.post("/team/join", {
    "teamId": joinTeamId.value,
    "password": password.value
  });
  if (result?.data.code === 200) {
    showSuccessToast('加入成功');
    joinTeamId.value = "";
    password.value = ""
    window.location.reload()
  } else {
    showFailToast('加入失败，' + result.data.description);
    joinTeamId.value = "";
    password.value = ""
  }
}
const doCancel = () => {
  joinTeamId.value = "";
  password.value = ""
}
/**
 * 修改队伍
 * @param teamId
 */
const doUpdateTeam = (teamId: number) => {
  router.push({
    path: '/team/update',
    query: {
      teamId
    }
  })
}
/**
 * 解散队伍
 * @param teamId
 */
const doDeleteTeam = async (teamId: number) => {
  const result = await request.post("/team/delete", {
    teamId
  });
  if (result?.data.code === 200) {
    showSuccessToast('解散成功');
    window.location.reload()
  } else {
    showFailToast('解散失败，' + result.data.description);
  }
}
/**
 * 退出队伍
 * @param teamId
 */
const doQuitTeam = async (teamId: number) => {
  const result = await request.post("/team/quit", {
    teamId
  });
  if (result?.data.code === 200) {
    showSuccessToast('成功退出');
    window.location.reload()
  } else {
    showFailToast('退出失败，' + result.data.description + ':' + result.data.message);
  }
}
</script>

<style scoped>

</style>